package com.athl.netty.nio;

import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.SelectionKey;
import java.nio.channels.Selector;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.util.Iterator;
import java.util.Set;

/**
 * @author hl
 * @Data 2020/8/29
 */
public class NioServer {

    public static void main(String[] args) throws Exception {
        // ServerSocket
        ServerSocketChannel serverSocketChannel = ServerSocketChannel.open();
        // Selector
        Selector selector = Selector.open();
        // 绑定端口
        serverSocketChannel.socket().bind(new InetSocketAddress(6666));
        serverSocketChannel.configureBlocking(false);
        // 把serverSocketChannel 注册到Selector , 事件为OP_ACCEPT
        serverSocketChannel.register(selector, SelectionKey.OP_ACCEPT);
        // 等待客户端连接
        while (true) {
            // 1000ms后还是无相关的事件
            if (selector.select(1000) == 0) {
                System.out.println("服务器无连接");
                continue;
            }
            // 否则 , 获取到相关的SelectedKeys集合
            Set<SelectionKey> selectedKeys = selector.selectedKeys();
            //遍历
            Iterator<SelectionKey> keyIterator = selectedKeys.iterator();
            while (keyIterator.hasNext()) {
                SelectionKey selectionKey = keyIterator.next();
                // 根据key对应的channel发生的事件做处理
                if (selectionKey.isAcceptable()) { /*  OP_ACCEPT */
                    SocketChannel socketChannel = serverSocketChannel.accept();
                    System.out.println("客户端已连接" + socketChannel.hashCode());
                    socketChannel.configureBlocking(false);
                    socketChannel.register(selector, SelectionKey.OP_READ, ByteBuffer.allocate(1024));
                    socketChannel.close();
                }
                if (selectionKey.isReadable()) {
                    SocketChannel channel = (SocketChannel) selectionKey.channel();
                    ByteBuffer buffer = (ByteBuffer) selectionKey.attachment();
                    channel.read(buffer);
                    System.out.println("form客户端:" + new String(buffer.array()));
                }
                // 手动从Set中移除这个selectKey
                keyIterator.remove();
            }
        }
    }
}
